package com.java.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ExecutorStopTest {

    public static void main(String[] args) throws InterruptedException {
        // 创建一个固定大小的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(4);

        // 提交一些任务给线程池
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executorService.execute(() -> {
                if (finalI == 5) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(">>>>>>> " + finalI);
            });
        }


        // 关闭线程池，不再接受新任务，但会继续执行已提交的任务
        executorService.shutdown();

        /*// 方式一
        while (!executorService.awaitTermination(2, TimeUnit.SECONDS)) {

        }*/


        // 方式二
        for (; !executorService.awaitTermination(2, TimeUnit.SECONDS) ;) {

        }

        System.out.println("all done");

    }
}
